//
//  OIDocument.m
//  OrchIDE
//
//  Created by local22 on 8/13/07.
//  Copyright __MyCompanyName__ 2007 . All rights reserved.
//

#import "OIDocument.h"
#import "OIEmulator.h"
#import "OIEmulatorWindowController.h"
#import "OIMemoryWindowController.h"

NSString *OIDocumentUniformTypeIdentifier = @"com.googlecode.p.orchid4k.orchide.emulator";

@implementation OIDocument

- (id)initWithType:(NSString *)typeName error:(NSError **)outError
{
    self = [super initWithType:typeName error:outError];
    if(!self) {
		return nil;
	}

	_emulator = [[OIEmulator alloc] init];

    return self;
}

- (void)dealloc
{
	[_emulator release];

	[super dealloc];
}

- (void)setEmulator:(OIEmulator *)emulator
{
	if(emulator == _emulator) {
		return;
	}
	
	[_emulator release];
	_emulator = [emulator retain];
	
	for(NSWindowController *controller in [self windowControllers]) {
		if([controller respondsToSelector:@selector(setEmulator:)]) {
			[(id)controller setEmulator:_emulator];
		}
	}
}

- (void)makeWindowControllers
{
	OIEmulatorWindowController *emulatorWindowController = [[OIEmulatorWindowController alloc] init];
	[emulatorWindowController setEmulator:_emulator];
	[self addWindowController:emulatorWindowController];
	[emulatorWindowController release];	
}

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
	if([typeName isEqualToString:OIDocumentUniformTypeIdentifier]) {
		return [NSKeyedArchiver archivedDataWithRootObject:_emulator];
	}

    if ( outError != NULL ) {
		*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
	}
	return nil;
}

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
	if([typeName isEqualToString:OIDocumentUniformTypeIdentifier]) {
		OIEmulator *emulator = [NSKeyedUnarchiver unarchiveObjectWithData:data];
		if(emulator) {
			[self setEmulator:emulator];
			return YES;
		}
	}

    if ( outError != NULL ) {
		*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
	}
    return NO;
}

@end
